import time

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from app import models


# Create your views here.
# 验证登录装饰器
def check_login(func):
    def warpper(request, *args, **kwargs):
        is_login = request.session.get('IS_LOGIN', False)
        if is_login:
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect("/login")

    return warpper


def login_view(request):
    if request.method == 'POST':
        user_name = request.POST.get('user_name', '')
        pass_word = request.POST.get('pwd', '')
        user = models.User.objects.filter(user_name=user_name, pwd=pass_word)  # 读取该用户信息
        if user:  # 如果存在
            if pass_word == user[0].pwd:
                request.session['IS_LOGIN'] = True
                request.session['user_name'] = user_name
                request.session['user_id'] = user[0].id
                return index_data(request)
                user_name = models.User.objects.all()
                return render(request, 'index.html', {"user_name": user_name})
            else:
                return render(request, 'login.html', {'error': '用户不存在！'})

    elif request.method == "GET":
        uid = request.session.get("user_id", None)
        if uid:
            return index_data(request)
        else:
            return render(request, 'login.html')
    else:
        return render(request, 'login.html')


# 退出登录
def login_out(request):
    request.session.flush()
    return render(request, 'login.html')


# 注册
def register_view(request):
    if request.method == "GET":
        return render(request, 'register.html')
    elif request.method == "POST":
        user_name = request.POST.get('user_name', '')
        pass_word_1 = request.POST.get('pwd', '')
        pass_word_2 = request.POST.get('cpwd', '')
        phone = request.POST.get('phone', '')
        if models.User.objects.filter(user_name=user_name):
            return render(request, 'register.html', {'error', '用户已存在！'})
        #
        if pass_word_1 != pass_word_2:
            return render(request, 'register.html', {'error', '两次密码不一致~'})
        user = models.User()
        user.user_name = user_name
        user.pwd = pass_word_1
        user.phone = phone
        user.save()
        return render(request, 'login.html')
    else:
        return render(request, 'register.html')


def index_data(request):
    goods_type = models.Type.objects.all()
    goods_dict = {}
    for type in goods_type:
        good_list = models.Goods.objects.filter(type__id=type.id)[:4]
        goods_dict[type] = good_list
    #     print(type.title_img)
    # print(goods_dict)
    return render(request, 'index.html', {"good_list": goods_dict, 'goods_type': goods_type,
                                          "user_name": request.session.get("user_name", None)})


# 首页
def index_view(request):
    if request.method == "GET":
        return index_data(request)


# 商品详情
def goodDetail(request, id):
    good_detail = models.Goods.objects.get(id=id)
    return render(request, 'detail.html', {"good": good_detail, 'user_name': request.session.get('user_name', None)})


# 購物車
@check_login
def cart_view(request):
    if request.method == "POST":
        # 获取前端传过来的数据
        uid = request.session['user_id']
        good_id = request.POST.get("good_id")
        num = request.POST.get("num")
        # 判断该用户的购物车是否存在商品数量
        cart = models.Cart.objects.filter(user__id=uid, goods__id=good_id).first()
        if cart:
            # 如果商品存在购物车，则修改购物车商品数量
            cart.num = cart.num + int(num)
            cart.save()
            # 如果商品不存在，则把商品添加购物车
        else:
            cart = models.Cart.objects.create(
                user_id=uid,
                num=int(num)
            )
            good = models.Goods.objects.get(id=good_id)
            cart.goods.add(good)
        return HttpResponse({"status": 1, "msg": "添加购物车成功"})
    elif request.method == "GET":
        uid = request.session['user_id']  # 获取用户ID
        list = []
        #
        cart_list = models.Cart.objects.filter(user_id=uid)
        total_price = 0  # 计算购物车所有商品总价
        count = 0
        for item in cart_list:
            goods = item.goods.first()
            goodDic = {}
            goodDic["good_name"] = goods.good_name
            goodDic["price"] = goods.price
            goodDic["unit"] = goods.unit
            goodDic["num"] = item.num
            goodDic["ing_url"] = goods.ing_url
            total = item.num * goods.price
            goodDic["good_name"] = total
            count += 1
            total_price += total
            list.append(goodDic)
        return render(request, 'cart.html', {"list": list, "total_price": total_price, "count": count,
                                             'user_name': request.session.get('user_name', None)})
    else:
        return render(request, 'cart.html', {'user_name': request.session.get('user_name', None)})


# 訂單
@check_login
def user_center_order_view(request,id):
    if request.method == "GET":
        if id>0:
            uid = request.session['user_id']
            list=[]
            order = models.Order.objects.get(user_id=uid,id=id)
            order_datail_list=models.OrderDetail.objects.filter(order__id=id)
            total_price = 0  # 计算购物车所有商品总价
            count = 0
            for item in order_datail_list:
                goodDic = {}
                goodDic["good_name"] = item.good_name
                goodDic["price"] = item.price
                goodDic["unit"] = "克"
                goodDic["num"] = item.num
                goodDic["ing_url"] = item.ing_url
                total = item.num * item.price
                goodDic["good_name"] = total
                count += 1
                total_price += total
                list.append(goodDic)
            return render(request, 'place_order.html',
                              {"list": list, "total_price": total_price, "count": count, "address": order,"order_id":id
                                  , 'user_name': request.session.get('user_name', None)})
        else:
            uid = request.session['user_id']
            #根据用户ID读取用户数据
            order_list = models.Order.objects.filter(user__id=uid)
            dic={}
            for order in order_list:
                good_list=models.OrderDetail.objects.filter(order__id=order.id)
                dic[order]=good_list
            return render(request, 'user_center_order.html',
                          {"goods": dic,'user_name': request.session.get('user_name', None)})
    elif request.method == "POST":
        uid = request.session['user_id']
        pay_status = request.POST.get('pay_status')
        order_id=request.POST.get('order_id')
        order=models.Order.objects.get(id=order_id,user_id=uid)
        if order:
            # 批量更新sava更新一条
            status = 1
            if int(pay_status) in [2,3,4]:
                status = 2
            order.status = status
            order.pay_status=pay_status
            order.save()
            return JsonResponse({"status": 1, "msg": "下单成功"})
        else:
            return JsonResponse({"status": 0, "msg": "订单不存在"})

# 地址
@check_login
def user_center_site(request):
    if request.method == "GET":
        uid = request.session['user_id']
        # 获取一条收货地址记录
        address = models.Address.objects.filter(user__id=uid).first()
        return render(request, 'user_center_site.html',
                      {"address": address, 'user_name': request.session.get('user_name', None)})

    elif request.method == "POST":
        uid = request.session['user_id']
        user_name = request.POST.get("user_name", None)
        address = request.POST.get("address", None)
        phone = request.POST.get("phone", None)
        if user_name == None or address == None or phone == None:
            return render(request, "user_center_site.html", {"error": "收件人，收货地址，联系电话不能为空"})
        address_mod = models.Address.objects.filter(user__id=uid).first()
        if address_mod:
            address_mod.user_name = user_name
            address_mod.address = address
            address_mod.phone = phone
            address_mod.save()
        else:
            address_mod = models.Address.objects.create(
                user_id=uid,
                user_name=user_name,
                address=address,
                phone=phone
            )
        # return JosnResponse({"status": 1, "msg": "添加联系人成功"})
        return render(request, "user_center_site.html",
                      {"address": address_mod, 'user_name': request.session.get('user_name', None)})
    else:
        return render(request, "user_center_site.html", {'user_name': request.session.get('user_name', None)})

# 提交订单
@check_login
def place_order_view(request):
    if request.method == "GET":
        uid = request.session['user_id']
        list = []
        cart_list = models.Cart.objects.filter(user_id=uid)
        total_price = 0  # 商品总价
        count = 0   # 商品数量
        # 获取收货地址
        addr = models.Address.objects.filter(user_id=uid).first()
        # 如果收货地址未添加，则转到添加收货地址页面
        if addr:
            pass
        else:
            return render(request, 'user_center_site.html', {'user_name': request.session.get('user_name', None)})
        # 遍历购物车，读取购物车数据
        for item in cart_list:
            goods = item.goods.first()
            goodDic = {}
            goodDic["good_name"] = goods.good_name
            goodDic["price"] = goods.price
            goodDic["unit"] = goods.unit
            goodDic["num"] = item.num
            goodDic["ing_url"] = goods.ing_url
            total = item.num * goods.price
            goodDic["good_name"] = total
            count += 1
            total_price += total
            list.append(goodDic)
        return render(request, 'place_order.html',
                      {"list": list, "total_price": total_price, "count": count, "address": addr
                          , 'user_name': request.session.get('user_name', None)})
    elif request.method=="POST":
        uid = request.session['user_id']
        pay_status=request.POST.get('pay_status')
        order_id=request.POST.get('order_id')

        addr = models.Address.objects.filter(user_id=uid).first()
        total_price = 0
        if addr:
            order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.',
                                                                                                                  '')[
                                                                        -7:]
            status = 1
            if int(pay_status) in [2,3,4]:
                status = 2
            order = models.Order.objects.create(
                status=status,
                user_id=uid,
                phone=addr.phone,
                user_name=addr.user_name,
                address=addr.address,
                order_no=order_no,
                pay_status=int(pay_status),
                total_price=0
            )
        # else:
       #      return render(request, 'user_center_site.html', {'user_name': request.session.get('user_name', None)})
       # # 添加订单
       #  order = models.Order.objects.create(
       #      status=1,
       #      user_id=uid,
       #      phone=phone,
       #      user_name=user_name,
       #      address=address,
       #      order_no=order_no,
       #      pay_status=int(pay_status),
       #      total_price=0
       #  )
            cart_list = models.Cart.objects.filter(user_id=uid)
            total_price=0
            count=0
            for item in cart_list:
                goods = item.goods.first()
                goodDic = {}
                goodDic["good_name"] = goods.good_name
                goodDic["price"] = goods.price
                goodDic["unit"] = goods.unit
                goodDic["num"] = item.num
                goodDic["ing_url"] = goods.ing_url
                total = item.num * goods.price
                goodDic["good_name"] = total
                count += 1
                total_price += total
            # list.append(goodDic)
            # goods = item.goods.first()
            # total = item.num * goods.price
            # total_price += total
        # 添加订单详情
                models.OrderDetail.objects.create(
                    good_name=goods.good_name,
                    price=goods.price,
                    num=item.num,
                    ing_url=goods.ing_url,
                    total_price=total,
                    order_id=order.id
                )
                # # 清空购物车
                cart_list.delete()
                # # 记录总付款
                order.total_price = total_price
                order.save()
        # if order:
        #     addr = models.Address.objects.filter(user_id=uid).first()
        #     if addr:
        #         # 批量更新sava更新一条
        #         order.status=2
        #         order.phone=addr.phone
        #         order.user_name = addr.user_name
        #         order.address = addr.address
        #         order.save()
            return JsonResponse({"status":1,"msg":"购买商品成功"})
        else:
            return JsonResponse({"status": 0, "msg": "请编辑收货地址"})
        # else:
        #     return JsonResponse({"status": 0, "msg": "购物车没有任何商品"})
    else:
        return render(request, 'place_order.html', {'user_name': request.session.get('user_name', None)})

@check_login
def user_center_info(request):
    uid = request.session['user_id']
    user=models.User.objects.get(id=uid)
    print(user)
    return render(request, 'user_center_info.html',{'user':user,'user_name': request.session.get('user_name', None)})
